package com.dizner.usbt;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity implements USBStoreyManager.OnUSEStatusChangeListener {

    private static final String TAG = "MainActivity";


    //    private MediaReceiver mUsbReceiver;
    private USBStoreyManager usbStoreyManager;
    private TextView tvUsbStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvUsbStatus = findViewById(R.id.tv_usb_status);
        usbStoreyManager = USBStoreyManager.getInstance(this);
//        new LifecycleRegistry(this).addObserver(usbStoreyManager);

        usbStoreyManager.setStatusChangeListener(this);
        //注册广播,监听USB插入和拔出
//        mUsbReceiver = new MediaReceiver(this, (UsbManager) getSystemService(Context.USB_SERVICE));
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
//        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
//        intentFilter.addAction(MediaReceiver.ACTION_USB_PERMISSION);
//        registerReceiver(mUsbReceiver, intentFilter);

        findViewById(R.id.btn_export).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                usbStoreyManager.exportFile(new File("/sdcard/123/23.txt"));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(mUsbReceiver);
        usbStoreyManager.onDestroy();
    }

    @Override
    public void onAttached() {
        tvUsbStatus.setText("USB已连接，正在准备");
    }

    @Override
    public void onDetached() {
        tvUsbStatus.setText("USB已断开");
    }

    @Override
    public void onReady(String volumeLabel, long capacity, long freeSpace) {
        tvUsbStatus.setText("USB已就绪,\n当前设备总计：" + USBStoreyManager.fSize(capacity) + "可用：" + USBStoreyManager.fSize(freeSpace));
    }

    @Override
    public void onExportStart() {
        showToast("开始导出");
    }


    @Override
    public void onExportCompleted() {
        showToast("导出完成");
    }

    @Override
    public void onExportError(String message) {
        showToast("导出失败：" + message);
    }

    @Override
    public void onUSBError(String message) {
        tvUsbStatus.setText(message);
    }


    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
